package com.ldk.admin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.framework.service.IOplogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.LostOrder;
import com.ldk.framework.entity.LostOrderImages;
import com.ldk.framework.entity.Platform;
import com.ldk.framework.enums.LostOrderStatus;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.service.ILostOrderService;
import com.ldk.framework.service.IPlatformService;

/**
 * 失物招领订单控制器
 * @author xiangwl
 * 2017年2月24日
 * com.ldk.admin.controller
 * LostOrderController
 */
@Controller
@RequestMapping("/lost")
public class LostOrderController extends BaseController {
	/**
	 * 路由地址
	 */
	private final String route = "lost";
	/**
	 * 模块名称
	 */
	private final String module = "失物招领";

	@Autowired
	private ILostOrderService lostOrderService;
	@Autowired
	private IPlatformService platformService;

	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		
		setLinks(map, "", "", module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add");
		map.addAttribute("route", route);
		map.addAttribute("module", module);
		map.addAttribute("platforms", getPlatforms());

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/lost/list_sj");
		} else {
			return new ModelAndView("/lost/list");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<LostOrder> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									       @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									       @RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
									       HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		LostOrder query = new LostOrder();
		if(!StringUtils.isBlank(searchKey)){
			query.setSearchKey(searchKey);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		
		Page<LostOrder> result = lostOrderService.selectPageList("", query, pageable);
		
		LigerUIGridResult<LostOrder> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map,HttpServletRequest request,
							HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		map.addAttribute("module", module);
		map.addAttribute("platforms", getPlatforms());
		
		LostOrder model = new LostOrder();
		
		return new ModelAndView("/lost/info","model",model);
	}
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public ModelAndView insert(@ModelAttribute("model") LostOrder model,
							   @RequestParam(value="files",required=false,defaultValue="") MultipartFile[] files,
							   RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		try{
			if(files == null || files.length < 1){
				rst.AddError("请选择物品图片");
				return new ModelAndView("redirect:/"+route+"/add");
				
			}
			String orderNo = SystemUtil.generateOrderNo(TripNoType.SW.getPrefix());
			List<LostOrderImages> images = new ArrayList<LostOrderImages>();
			for (MultipartFile file : files) {
				if(file == null || file.isEmpty()) continue;
				Map<String, String> fileMap = saveImage(module, file, false, true);
				if(fileMap == null || !fileMap.containsKey("link") || StringUtils.isBlank(fileMap.get("link")))
					continue;
				LostOrderImages image = new LostOrderImages();
				image.setImage(fileMap.get("link"));
				image.setOrderNo(orderNo);
				
				images.add(image);
			}
			if(images.isEmpty()){
				rst.AddError("保存物品图片失败");
				return new ModelAndView("redirect:/"+route+"/add");
			}
			model.setOrderNo(orderNo);
			model.setPublisher(getAdminUserName(request));
			model.setPlatform("16");//16为后台管理的平台值
			model.setStatus(LostOrderStatus.Publish.getValue());
			model.setCreateTime(SystemUtil.getAllSeconds());

			//操作日志
			this.insertOplog(request,module,"","","添加:"+model.getGoodsName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		    Boolean success = lostOrderService.publish("", model, images);
		    if(success){
		    	rst.AddOk("添加"+module+"成功");
		    }
		    else{
		    	rst.AddError("添加"+module+"失败");
		    }
		}
		catch(Exception e){
			rst.AddError("添加"+module+"失败");
			logger.error(e.getMessage());
		}
		return new ModelAndView("redirect:/"+route+"/add");
	}
	
	/**
	 * 浏览
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/view/{orderNo}")
	public ModelAndView view(@PathVariable(value="orderNo") String orderNo, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setViewMode(map, ViewMode.View);
		LostOrder query = new LostOrder();
		query.setOrderNo(orderNo);
		LostOrder model = lostOrderService.selectByKey("", query);
		
		map.addAttribute("module", module);
		map.addAttribute("platforms", getPlatforms());
		
		return new ModelAndView("/lost/info","model", model);
	}
	
	@ResponseBody
	@RequestMapping("/remove/{orderNo}")
	public ResponseResult remove(@PathVariable(value="orderNo") String orderNo, HttpServletRequest request){
		
		ResponseResult rst = new ResponseResult();
		if(StringUtils.isBlank(orderNo))
		{
			rst.AddError("删除"+module+"错误");
			return rst;
		}
		Boolean successed = false;
		try{
			LostOrder query = new LostOrder();
			query.setOrderNo(orderNo);
			LostOrder lostOrder = lostOrderService.selectByKey("", query);
			//操作日志
			this.insertOplog(request,module,"","","删除:"+lostOrder.getGoodsName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			int row = lostOrderService.deleteByKey("", query);
			successed = row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(successed){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}
		
		return rst;
	}
	
	/**
	 * 获取系统平台
	 * @return
	 */
	private List<Platform> getPlatforms(){
		Platform query = new Platform();
		query.setEnabled(true);
		
		List<Platform> platforms = platformService.selectList("", query);
		
		return platforms;
	}
}
